package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

// 基本的表单文件上传
@Controller
public class UploadController {

    private static String UPLOADED_FOLDER = "E://temp//";

    @GetMapping("/")
    public String jumpIndex(){
        return "upload";
    }
    @GetMapping("/uploadstatus")
    public String uploadstatus(){
        return "uploadstatus";
    }


    /**
     * 表单单文件上传
     * @param file
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/upload") // //new annotation since 4.3
    public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:/uploadstatus";
        }

        try {
            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            Path dir = Paths.get(UPLOADED_FOLDER);
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            // Create parent dir if not exists
            if(!Files.exists(dir)) {
                Files.createDirectories(dir);
            }
            Files.write(path, bytes);
            redirectAttributes.addFlashAttribute("getOriginalFilename",
                     file.getOriginalFilename());
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");

        } catch (IOException e) {
            redirectAttributes.addFlashAttribute("message", "Server throw IOException");
            e.printStackTrace();
        }
        return "redirect:/uploadstatus";
    }

    /**
     * 表单多文件上传
     * @param files
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/mulupload") // //new annotation since 4.3
    public String muluploadFileUpload(@RequestParam("files") MultipartFile[] files,
                                   RedirectAttributes redirectAttributes) {
        // 存储上传成功的文件名，响应给客户端
        List<String> list = new ArrayList<>();
        // 判断文件数组长度
        if(files.length <= 0){
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:/uploadstatus";
        }
        for(MultipartFile file : files){
            // 源文件名
            String originalFilename = file.getOriginalFilename();
            // 文件格式
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 新文件名，避免文件名重复，造成文件替换问题
            String fileName = UUID.randomUUID()+"."+suffix;
            // 文件全路径
            File targetFile = new File(UPLOADED_FOLDER+fileName);

            // 判断文件存储目录是否存在，不存在则新建目录
            if(!targetFile.getParentFile().exists()){
                targetFile.getParentFile().mkdir();
            }
            try {
                // 将图片保存
                file.transferTo(targetFile);
                list.add(originalFilename);
                StringBuffer stringBuffer  = new StringBuffer();
                for (String fileame:list) {
                    stringBuffer.append(fileame+";");
                }
                redirectAttributes.addFlashAttribute("message",
                        "You successfully uploaded '" + stringBuffer + "'");
            } catch (IOException e) {
                redirectAttributes.addFlashAttribute("message", "Server throw IOException");
                e.printStackTrace();
            }
        }
        return "redirect:/uploadstatus";
}



//    @PostMapping("/upload")
//    public String singleFileUpload(@RequestParam("file") MultipartFile file,
//                                   RedirectAttributes redirectAttributes) {
//        if (file.isEmpty()) {
//            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
//            return "redirect:/uploadstatus";
//        }
//
//        try {
//            // Get the file and save it somewhere
//            byte[] bytes = file.getBytes();
//            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
//            Files.write(path, bytes);
//
//            redirectAttributes.addFlashAttribute("message",
//                    "You successfully uploaded '" + file.getOriginalFilename() + "'");
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        return "redirect:/uploadstatus";
//    }

}
